<template>
  <div class="activity-management-container">
    <el-card class="filter-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h3>活动报名列表</h3>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="活动标题">
          <el-input v-model="searchForm.title" placeholder="请输入活动标题" clearable />
        </el-form-item>
        
        <el-form-item label="活动状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="未发布" value="1" />
            <el-option label="已发布" value="2" />
            <el-option label="进行中" value="3" />
            <el-option label="已结束" value="4" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><search /></el-icon> 搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><refresh /></el-icon> 重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <div class="activity-card-container">
      <el-card 
        class="activity-card" 
        shadow="hover" 
        v-for="activity in activityList" 
        :key="activity.id"
      >
        <template #header>
          <div class="activity-card-header">
            <h3>{{ activity.title }}</h3>
            <el-tag :type="getStatusType(activity.status)">{{ getStatusName(activity.status) }}</el-tag>
          </div>
        </template>
        
        <div class="activity-card-content">
          <div class="activity-info">
            <p>
              <el-icon><location /></el-icon>
              <span>{{ activity.location }}</span>
            </p>
            <p>
              <el-icon><time /></el-icon>
              <span>开始时间: {{ formatDateTime(activity.startTime) }}</span>
            </p>
            <p>
              <el-icon><time /></el-icon>
              <span>结束时间: {{ formatDateTime(activity.endTime) }}</span>
            </p>
            <p>
              <el-icon><user /></el-icon>
              <span>组织者ID: {{ activity.organizerId }}</span>
            </p>
            <p>
              <el-icon><people /></el-icon>
              <span>最大人数: {{ activity.maxParticipants }}</span>
            </p>
          </div>
          
          <div class="activity-content">
            <p>{{ activity.content }}</p>
          </div>
          
          <div class="activity-actions">
            <el-button 
              type="primary" 
              :disabled="activity.status !== 2 && activity.status !== 3 || isSigningUp.includes(activity.id)"
              :loading="isSigningUp.includes(activity.id)"
              @click="openSignupDialog(activity)"
            >
              <el-icon><check-circle /></el-icon> 报名参加
            </el-button>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 分页组件 -->
    <div class="pagination" v-if="total > 0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
    
    <!-- 报名对话框 -->
    <el-dialog
      v-model="signupDialogVisible"
      title="活动报名"
      width="40%"
      @close="resetSignupForm"
    >
      <el-form :model="signupForm" :rules="signupRules" ref="signupFormRef" label-width="120px">
        <el-form-item label="活动名称" prop="activityName">
          <el-input v-model="signupForm.activityName" disabled />
        </el-form-item>
        
        <el-form-item label="报名备注" prop="remarks">
          <el-input 
            v-model="signupForm.remarks" 
            type="textarea" 
            :rows="3" 
            placeholder="请输入报名备注（选填）"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="signupDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSignup" :loading="signupLoading">
            确认报名
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search,
  Refresh,
  Location,
  Time,
  User,
  People,
  CheckCircle
} from '@element-plus/icons-vue';
import request from '@/utils/request';

// 搜索表单
const searchForm = reactive({
  title: '',
  status: ''
});

// 活动列表数据
const activityList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const loading = ref(false);

// 报名相关
const signupDialogVisible = ref(false);
const signupForm = reactive({
  activityId: null,
  activityName: '',
  userId: '',
  status: 1, // 1-已报名
  remarks: ''
});
const signupRules = reactive({
  activityName: [
    { required: true, message: '请选择活动', trigger: 'change' }
  ]
});
const signupFormRef = ref(null);
const signupLoading = ref(false);
const isSigningUp = ref([]); // 存储正在报名的活动ID数组

// 生命周期钩子
onMounted(() => {
  fetchActivityList();
});

// 获取活动列表
const fetchActivityList = async () => {
  loading.value = true;
  
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      title: searchForm.title || undefined,
      status: searchForm.status || undefined
    };
    
    const response = await request.get('/activity-service/activity/list', { params });
    
    if (response.code === 200) {
      activityList.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取活动列表失败');
    }
  } catch (error) {
    ElMessage.error('获取活动列表失败，请重试');
    console.error('获取活动列表错误:', error);
  } finally {
    loading.value = false;
  }
};

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchActivityList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.title = '';
  searchForm.status = '';
  currentPage.value = 1;
  fetchActivityList();
};

// 处理分页大小变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  fetchActivityList();
};

// 处理当前页变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  fetchActivityList();
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  const date = new Date(dateTime);
  return date.toLocaleString();
};

// 获取状态名称
const getStatusName = (status) => {
  const statuses = {
    1: '未发布',
    2: '已发布',
    3: '进行中',
    4: '已结束'
  };
  return statuses[status] || '未知';
};

// 获取状态标签类型
const getStatusType = (status) => {
  const types = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'primary'
  };
  return types[status] || 'info';
};

// 打开报名对话框
const openSignupDialog = (activity) => {
  // 从localStorage获取用户ID（登录时存储）
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  const userId = userInfo.id || '';
  
  if (!userId) {
    ElMessage.warning('请先登录再报名活动');
    return;
  }
  
  // 填充表单数据
  Object.assign(signupForm, {
    activityId: activity.id,
    activityName: activity.title,
    userId: userId,
    status: 1,
    remarks: ''
  });
  
  signupDialogVisible.value = true;
  
  // 重置表单验证
  nextTick(() => {
    if (signupFormRef.value) {
      signupFormRef.value.clearValidate();
    }
  });
};

// 重置报名表单
const resetSignupForm = () => {
  Object.assign(signupForm, {
    activityId: null,
    activityName: '',
    userId: '',
    status: 1,
    remarks: ''
  });
  
  if (signupFormRef.value) {
    signupFormRef.value.resetFields();
  }
};

// 处理报名
const handleSignup = async () => {
  if (!signupFormRef.value) return;
  
  const valid = await signupFormRef.value.validate();
  if (!valid) return;
  
  try {
    signupLoading.value = true;
    isSigningUp.value.push(signupForm.activityId);
    
    // 准备报名数据
    const signupData = {
      activityId: signupForm.activityId,
      userId: signupForm.userId,
      status: signupForm.status,
      remarks: signupForm.remarks
    };
    
    // 调用报名API
    const response = await request.post('/signup-service/signup/add', signupData);
    
    if (response.code === 200) {
      ElMessage.success('报名成功');
      signupDialogVisible.value = false;
      // 刷新活动列表
      fetchActivityList();
    } else {
      ElMessage.error(response.message || '报名失败');
    }
  } catch (error) {
    ElMessage.error('报名失败，请重试');
    console.error('报名错误:', error);
  } finally {
    signupLoading.value = false;
    isSigningUp.value = isSigningUp.value.filter(id => id !== signupForm.activityId);
  }
};
</script>

<style scoped lang="scss">
.activity-management-container {
  padding: 15px;
}

.filter-card {
  margin-bottom: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-top: 8px;
}

.activity-card-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.activity-card {
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateY(-3px);
  }
  
  .activity-card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 15px;
  }
  
  .activity-card-content {
    display: flex;
    flex-direction: column;
    gap: 10px;
    padding: 0 15px 15px;
    
    .activity-info {
      display: grid;
      grid-template-columns: 1fr;
      gap: 6px;
      
      p {
        display: flex;
        align-items: center;
        gap: 6px;
        margin: 0;
      }
    }
    
    .activity-content {
      margin-top: 8px;
      padding-top: 8px;
      border-top: 1px solid #ebeef5;
    }
    
    .activity-actions {
      margin-top: 10px;
      text-align: center;
    }
  }
}

.pagination {
  margin-top: 15px;
  text-align: right;
}
</style>